package com.aacar.service.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import com.aacar.constant.ConsFiled;
import com.aacar.constant.RedisConsField;
import com.aacar.constant.SmsFiled;
import com.aacar.dto.MessageDto;
import com.aacar.dto.SmsDto;
import com.aacar.service.MessageService;
import com.aacar.utils.RedisCacheManagerUtil;
import com.aacar.utils.SpringContextUtil;
import com.aacar.utils.TokenUtil;
import com.aacar.utils.message.SmSUtils;
import com.aacar.vo.MessageVo;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;

/**
 * 
 * @author wangh
 * 消息服务
 *
 */
@Repository("messageService")
public class MessageServiceImpl implements MessageService {
	
	private Log logger = LogFactory.getLog(MemberServiceImpl.class);
	
	@Autowired  
	private RedisTemplate<String,String> redisTemplate; 
	
	/**
	 * 发送短信
	 */
	public MessageVo sendShortMessage(MessageDto messageDto) {
		MessageVo mv = new MessageVo();
		//成功
		String code = TokenUtil.generateSmsCode();//生成6位验证码
		RedisCacheManagerUtil rmu = (RedisCacheManagerUtil) SpringContextUtil.getBean(ConsFiled.REDIE_CACHE);
		
		//注释掉的代码为测试代码
//		String code = "1234";
//		if("0".equals(messageDto.getFlag())) {
//			mv.setSuccess(true);
//			mv.setMessage("发功成功.");
//			rmu.set(ConsFiled.PRE_CODE_1+messageDto.getPhoneNo(), code, ConsFiled.VALICODE_TIME);
//			return mv;
//		}else if("1".equals(messageDto.getFlag())) {
//			mv.setSuccess(true);
//			mv.setMessage("发功成功.");
//			rmu.set(ConsFiled.PRE_CODE_2+messageDto.getPhoneNo(), code, ConsFiled.VALICODE_TIME);
//			return mv;
//		}
		//下面代码为上线的时候使用
		try {
			//注册发送验证码
			if("0".equals(messageDto.getFlag())) {
				SmsDto smsDto = new SmsDto();
				smsDto.setCode(code);
				SendSmsResponse response = SmSUtils.sendSms(messageDto.getPhoneNo(), ConsFiled.Register_SMS_Template, JSON.toJSONString(smsDto));
				logger.info("发送短信返回值为:code:"+response.getCode()+"===message:"+response.getMessage());
				if(SmsFiled.OK.equals(response.getCode())) {
					mv.setSuccess(true);
					if(null != response.getMessage())
						mv.setMessage(response.getMessage());
					else {
						mv.setMessage("发功成功.");
					}
				}else {
					mv.setSuccess(false);
					mv.setMessage(response.getMessage());
				}
				rmu.set(ConsFiled.PRE_CODE_1+messageDto.getPhoneNo(), code, ConsFiled.VALICODE_TIME);
			}
			//忘记密码发送验证码
			else if("1".equals(messageDto.getFlag())) {
				SmsDto smsDto = new SmsDto();
				smsDto.setCode(code);
				SendSmsResponse response = SmSUtils.sendSms(messageDto.getPhoneNo(), ConsFiled.ResetPassword_SMS_Template, JSON.toJSONString(smsDto));
				logger.info("发送短信返回值为:code:"+response.getCode()+"===message:"+response.getMessage());
				if(SmsFiled.OK.equals(response.getCode())) {
					mv.setSuccess(true);
					if(null != response.getMessage())
						mv.setMessage(response.getMessage());
					else {
						mv.setMessage("发功成功.");
					}
				}else {
					mv.setSuccess(false);
					mv.setMessage(response.getMessage());
				}
				rmu.set(ConsFiled.PRE_CODE_2+messageDto.getPhoneNo(), code, ConsFiled.VALICODE_TIME);
			}
		}catch(Exception e) {
			e.printStackTrace();
			mv.setSuccess(false);
			mv.setMessage(e.getMessage());
		}
		return mv;
	}
	
	/**
	 * 校验短信
	 */
	public MessageVo validatorShortMessage(MessageDto messageDto) {
		MessageVo mv = new MessageVo();
		RedisCacheManagerUtil rmu = (RedisCacheManagerUtil) SpringContextUtil.getBean(ConsFiled.REDIE_CACHE);
		try {
			Object result = null;
			//注册验证码
			if("0".equals(messageDto.getFlag())) {
				String key = ConsFiled.PRE_CODE_1+messageDto.getPhoneNo();
				result = rmu.get(key);
			}
			//忘记密码
			if("1".equals(messageDto.getFlag())) {
				result = rmu.get(ConsFiled.PRE_CODE_2+messageDto.getPhoneNo());
			}
			String code = "";
			if("0".equals(messageDto.getFlag())) {
				code = retrieveImageCode(messageDto.getPhoneNo(),"1");//注册验证码
			}
			if("1".equals(messageDto.getFlag())) {
				code = retrieveImageCode(messageDto.getPhoneNo(),"2");//注册验证码
			}
			if(null == result) {
				mv.setSuccess(false);
				mv.setMessage(ConsFiled.MESSAGE_ERROR_INFO);
				return mv;
			}
			if(!result.equals(messageDto.getCode())) {
				mv.setSuccess(false);
				mv.setMessage(ConsFiled.MESSAGE_ERROR_INFO);
			}else{
				mv.setSuccess(true);
				mv.setMessage(code);
			}
		}catch(Exception e) {
			logger.error("短信验证错误,手机号为:"+messageDto.getPhoneNo(),e);
			mv.setSuccess(false);
			mv.setMessage(e.getMessage());
		}
		return mv;
	}
	
	//获取图片验证码
	public String retrieveImageCode(String phoneNo,String type) {
		ValueOperations<String, String> valueOper = redisTemplate.opsForValue();  
//		String code = RandomCharData.createRandomCharData(6);
		int codes = (int) ((Math.random()*9+1)*100000);//生成6位随机数
		String code = String.valueOf(codes);
		if(ConsFiled.Code_Type_1.equals(type)) {
			valueOper.set(RedisConsField.pre_register_code+phoneNo+code, phoneNo);
		}else if(ConsFiled.Code_Type_2.equals(type)){
			valueOper.set(RedisConsField.pre_resetpassword_code+phoneNo+code, phoneNo);
		}
		return code;
	}
	
	//检验验证码
	public String validatorImageCode(String type,String phoneNo,String code) {
		ValueOperations<String, String> valueOper = redisTemplate.opsForValue();  
		String result = "";
		if(ConsFiled.Code_Type_1.equals(type)) {
			result = valueOper.get(RedisConsField.pre_register_code+phoneNo+code);//注册
		}else if(ConsFiled.Code_Type_2.equals(type)){
			result = valueOper.get(RedisConsField.pre_resetpassword_code+phoneNo+code);//重置密码
		}
		return result;
	}

}
